package com.cloud.common.rpc;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;

/**
 * RPC客户端
 *
 * @author fengwenjin
 */
@Slf4j
@Component
public class RPCClient implements ApplicationListener<ContextClosedEvent> {
    private Map<String, Channel> channelMap = new HashMap<>(512);

    @Autowired
    private ClientHandler clientHandler;

    private NioEventLoopGroup eventLoopGroup;
    private Bootstrap bootstrap;

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        close();
    }

    public void close() {
        if (eventLoopGroup != null) {
            eventLoopGroup.shutdownGracefully();

            eventLoopGroup = null;
            bootstrap = null;
        }
    }

    public void send(String host, int port, RPCMessage message) throws Exception {
        Channel channel = getChannel(host, port);
        if (channel == null) {
            String errorMsg = getHostKey(host, port) + " connection failure";
            throw new SocketException(errorMsg);
        }
        channel.writeAndFlush(message);
    }

    private Channel getChannel(String host, int port) throws Exception {
        String key = getHostKey(host, port);
        Channel channel = channelMap.get(key);
        if (channel != null && !channel.isActive()) {
            channelMap.remove(key);
            channel.close();
            channel = null;
        }
        if (channel == null) {
            synchronized (this) {
                channel = channelMap.get(key);
                if (channel == null) {
                    channel = connect(host, port);
                    channelMap.put(key, channel);
                }
            }
        }
        return channel;
    }

    private Channel connect(String host, int port) throws Exception {
        if (bootstrap == null) {
            createBootstrap();
        }
        ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
        if (channelFuture.isSuccess()) {
            return channelFuture.channel();
        }
        return null;
    }

    private void createBootstrap() {
        eventLoopGroup = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ChannelPipeline pipeline = socketChannel.pipeline();
                pipeline.addLast(new MessageEncoder());
                pipeline.addLast(new MessageDecoder());
                pipeline.addLast(clientHandler);
            }
        });
        runCleaner();
    }

    private void runCleaner() {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    ResponseFutureManager.clean();
                    Thread.sleep(500L);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        });
        thread.setName("RPC-Client-Cleaner");
        thread.setDaemon(true);
        thread.start();
    }

    private String getHostKey(String host, int port) {
        return host + ":" + port;
    }
}
